package cn.tudo.egweibo2.controller;

import cn.tudo.egweibo2.mapper.UserMapper;
import cn.tudo.egweibo2.pojo.dto.UserLoginDTO;
import cn.tudo.egweibo2.pojo.dto.UserRegDTO;
import cn.tudo.egweibo2.pojo.entity.User;
import cn.tudo.egweibo2.pojo.vo.UserVO;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.sun.org.apache.xml.internal.resolver.helpers.PublicId;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("v1/users/")
public class UserCotroller {
    //自动装配
    @Autowired
    private UserMapper userMapper;

    /**
     * 1.注册功能
     * RequestBody注解：将JavaScript对象转为JSON格式,并封装到DTO中.
     * 是否需要添加此注解的标准：
     *   1.Content-Type: application/x-www-form-urlencoded: 不加!!!
     *   2.Content-Type: application/json: 必须加!!!
     */
    @PostMapping("reg")
    public int reg(@RequestBody UserRegDTO userRegDTO){
        /*
            1.数据合法性校验[此处不做校验];
            2.确认用户名是否被占用[查询接口];
              SELECT id FROM user WHERE username=用户名
              2.1 被占用: return 2;
              2.2 未被占用: 插入数据表[插入接口], return 1;
         */
        //soutp + 回车
        log.debug("userRegDTO = " + userRegDTO);
        //确认用户名是否被占用
        UserVO userVO = userMapper.selectByUsername(userRegDTO.getUsername());
        if (userVO != null){//被占用
            return 2;
        }
        //存入数据
        User user = new User();
        BeanUtils.copyProperties(userRegDTO, user);
        user.setCreated(new Date());
        userMapper.insertUser(user);

        return 1; //注册成功
    }


    @PostMapping("login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session) {
        System.out.println("userLoginDTO = " + userLoginDTO);
        UserVO userVO = userMapper.selectByUsername(userLoginDTO.getUsername());
        if (userVO == null) {//用户名错误
            return 3;
        }
        if (userLoginDTO.getPassword().equals(userVO.getPassword())) {
            session.setAttribute("user", userVO);
            return 1;
        }
        return 2;
    }

    // 3.获取当前用户功能
    @GetMapping("currentUser")
    public UserVO currentUser(HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");
        return userVO;
    }

    @GetMapping("logout")
    public void logout(HttpSession session) {
        session.removeAttribute("user");


    }


}
